package com.example.opengl.render.magiccube

import android.opengl.GLES20
import android.opengl.GLES20.*
import com.example.opengl.R
import com.example.opengl.base.BufferHelper
import com.example.opengl.base.OpenGLUtils
import com.example.opengl.base.ShaderHelper
import com.example.opengl.base.TextResourceReader
import com.example.opengl.render.base.IDrawer
import java.nio.FloatBuffer

/**
 * @author: Mr.You
 * @create: 2023-08-08 15:10
 * @description:
 **/
class MagicCubeDrawer : IDrawer {

    private var mProgram = -1
    private var vertexFloatBuffer: FloatBuffer? = null
    private var textureFloatBuffer: FloatBuffer? = null
    private var vertexShader: Int = -1
    private var textureShader: Int = -1
    private var mRation = 1f
    private var mTextureIds: IntArray? = null


    override fun draw() {
        glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)
        //计算变换矩阵
        OpenGLUtils.transform(mProgram, mRation)

        glEnableVertexAttribArray(0)
        glEnableVertexAttribArray(1)

        glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, vertexFloatBuffer)
        glVertexAttribPointer(1, 2, GL_FLOAT, false, 0, textureFloatBuffer)

        //激活纹理
        glActiveTexture(GL_TEXTURE)
        //绘制纹理
        drawTexture()

        glDisableVertexAttribArray(0)
        glDisableVertexAttribArray(1)

    }

    private fun drawTexture() {
        val count = 4
        mTextureIds?.forEachIndexed { index, i ->
            val first = index * count
            glBindTexture(GL_TEXTURE_2D, i)
            glDrawArrays(GL_TRIANGLE_STRIP, first, count)
        }


    }

    override fun setTextureID(id: Int) {

    }

    override fun release() {

    }

    override fun setWorldSize(worldW: Int, worldH: Int) {
        glClearColor(0.1f, 0.2f, 0.3f, 0.4f)
        glViewport(0, 0, worldW, worldH)
        glEnable(GL_DEPTH_TEST)
        mRation = 1f * worldW / worldH
        initCoords()
        initShader()
        loadTexture()

    }

    private fun initCoords() {
        vertexFloatBuffer = BufferHelper.getFloatBuffer(MagicCubeModel.getVertex())
        textureFloatBuffer = BufferHelper.getFloatBuffer(MagicCubeModel.getTexture())
    }

    private fun initShader() {
        vertexShader =
            ShaderHelper.compileVertexShader(TextResourceReader.readTextFileFormResource(resourceId = R.raw.image_vertex_shader))
        textureShader =
            ShaderHelper.compileFragmentShader(TextResourceReader.readTextFileFormResource(resourceId = R.raw.image_fragment_shader))
        mProgram = ShaderHelper.linkProgram(vertexShader, textureShader)
        glUseProgram(mProgram)
    }

    private fun loadTexture() {
        mTextureIds = OpenGLUtils.loadTexture(MagicCubeModel.getMipmap())
    }


    override fun setVideoSize(videoW: Int, videoH: Int) {

    }
}